import React, { createContext, useContext, useReducer, ReactNode } from 'react';
import { AppState, Product, Category, ViewType } from '../types';

// 定义Action类型
type Action =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_CATEGORIES'; payload: Category[] }
  | { type: 'ADD_SELECTED_PRODUCT'; payload: Product }
  | { type: 'REMOVE_SELECTED_PRODUCT'; payload: string }
  | { type: 'SET_PRODUCT_AT_INDEX'; payload: { index: number; product: Product | null } }
  | { type: 'CLEAR_SELECTED_PRODUCTS' }
  | { type: 'SET_VIEW'; payload: ViewType }
  | { type: 'SET_SELECTED_CATEGORY'; payload: { categoryId: string | null; subcategoryId: string | null } };

// 初始状态
const initialState: AppState = {
  categories: [],
  selectedProducts: [],
  loading: false,
  error: null,
  currentView: 'selector',
  selectedCategoryId: null,
  selectedSubcategoryId: null,
};

// Reducer函数
const productReducer = (state: AppState, action: Action): AppState => {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload };
    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };
    case 'SET_CATEGORIES':
      return { ...state, categories: action.payload, loading: false };
    case 'ADD_SELECTED_PRODUCT':
      // 最多选择2个产品进行比较
      if (state.selectedProducts.length >= 2) {
        return state;
      }
      return {
        ...state,
        selectedProducts: [...state.selectedProducts, action.payload],
      };
    case 'REMOVE_SELECTED_PRODUCT':
      return {
        ...state,
        selectedProducts: state.selectedProducts.filter(p => p.id !== action.payload),
      };
    case 'SET_PRODUCT_AT_INDEX':
      const newSelectedProducts = [...state.selectedProducts];
      if (action.payload.product === null) {
        // 移除指定位置的产品
        newSelectedProducts.splice(action.payload.index, 1);
      } else {
        // 在指定位置设置产品
        if (action.payload.index < newSelectedProducts.length) {
          newSelectedProducts[action.payload.index] = action.payload.product;
        } else {
          newSelectedProducts.push(action.payload.product);
        }
      }
      return {
        ...state,
        selectedProducts: newSelectedProducts,
      };
    case 'CLEAR_SELECTED_PRODUCTS':
      return { ...state, selectedProducts: [] };
    case 'SET_VIEW':
      return { ...state, currentView: action.payload };
    case 'SET_SELECTED_CATEGORY':
      return { 
        ...state, 
        selectedCategoryId: action.payload.categoryId,
        selectedSubcategoryId: action.payload.subcategoryId,
        currentView: 'selector' // 选择新分类时切换到选择器视图
      };
    default:
      return state;
  }
};

// Context接口
interface ProductContextType {
  state: AppState;
  dispatch: React.Dispatch<Action>;
  addSelectedProduct: (product: Product) => void;
  removeSelectedProduct: (productId: string) => void;
  setProductAtIndex: (index: number, product: Product | null) => void;
  clearSelectedProducts: () => void;
  setView: (view: ViewType) => void;
  setSelectedCategory: (categoryId: string | null, subcategoryId: string | null) => void;
}

// 创建Context
const ProductContext = createContext<ProductContextType | undefined>(undefined);

// Provider组件
export const ProductProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [state, dispatch] = useReducer(productReducer, initialState);

  const addSelectedProduct = (product: Product) => {
    dispatch({ type: 'ADD_SELECTED_PRODUCT', payload: product });
  };

  const removeSelectedProduct = (productId: string) => {
    dispatch({ type: 'REMOVE_SELECTED_PRODUCT', payload: productId });
  };

  const clearSelectedProducts = () => {
    dispatch({ type: 'CLEAR_SELECTED_PRODUCTS' });
  };

  const setView = (view: ViewType) => {
    dispatch({ type: 'SET_VIEW', payload: view });
  };

  const setSelectedCategory = (categoryId: string | null, subcategoryId: string | null) => {
    dispatch({ type: 'SET_SELECTED_CATEGORY', payload: { categoryId, subcategoryId } });
  };

  const setProductAtIndex = (index: number, product: Product | null) => {
    dispatch({ type: 'SET_PRODUCT_AT_INDEX', payload: { index, product } });
  };

  return (
    <ProductContext.Provider
      value={{
        state,
        dispatch,
        addSelectedProduct,
        removeSelectedProduct,
        setProductAtIndex,
        clearSelectedProducts,
        setView,
        setSelectedCategory,
      }}
    >
      {children}
    </ProductContext.Provider>
  );
};

// Hook来使用Context
export const useProduct = () => {
  const context = useContext(ProductContext);
  if (context === undefined) {
    throw new Error('useProduct must be used within a ProductProvider');
  }
  return context;
}; 